package com.ushine.web.communication.netty;

import com.ushine.web.communication.netty.config.NettyConfig;
import com.ushine.web.communication.netty.handler.RegisterHandler;
import com.ushine.web.communication.netty.handler.SendEventHandler;
import com.ushine.web.communication.netty.proto.Message;
import com.ushine.web.communication.netty.service.INettyService;
import com.ushine.web.component.exception.ServiceException;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Service;

/**
 * @Author: yls
 * @Date 2022/5/11 10:58
 * @Description: netty通信服务端
 * @Version 1.0
 **/
@Slf4j
@Service
public class NettySocketServer implements ApplicationListener<ContextClosedEvent> {

    private static final String TAG = "netty-socket 通信服务端=》";

    /**
     * 属性【key】
     */
    public static final AttributeKey<String> ATTR_KEY = AttributeKey.valueOf("serialNumber");


    /**
     * 消息通道
     */
    private Channel channel;

    /**
     * netty配置
     */
    private NettyConfig nettyConfig;

    /**
     * netty消息处理
     */
    private INettyService nettyService;

    /**
     * 构造器
     */
    public NettySocketServer(NettyConfig nettyConfig, INettyService nettyService) {
        this.nettyConfig = nettyConfig;
        this.nettyService = nettyService;
    }


    /**
     * 功能描述:
     * 〈 初始化服务端 〉
     *
     * @return : void
     * @throws InterruptedException 线程中断异常
     * @author : yls
     * @date : 2022/5/11 11:02
     */
    public void initServer() throws InterruptedException {
        EventLoopGroup boos = new NioEventLoopGroup(1);
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            Integer port = nettyConfig.getPort();
            String ip = nettyConfig.getIp();
            ServerBootstrap server = new ServerBootstrap();
            server.group(boos, worker);
            server.channel(NioServerSocketChannel.class);
            server.option(ChannelOption.SO_BACKLOG, 1024);
            server.handler(new LoggingHandler(LogLevel.INFO));
            // 通道初始化
            server.childHandler(new ServerChannelInitializer(nettyService));
            ChannelFuture future = server.bind(ip, port).sync();
            log.info("{}启动成功，ip={},port={}", TAG, ip, port);
            ChannelFuture sync = future.channel().closeFuture().sync();
            this.channel = sync.channel();
        } finally {
            log.warn("{}通信服务端停止!", TAG);
            boos.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

    /**
     * 功能描述:
     * 〈 发送数据 〉
     *
     * @param serialNumber 主机序列号
     * @param instruction  发送的信息
     * @param sendEvent    消息发送处理器
     * @return : void
     * @author : yls
     * @date : 2022/5/11 11:08
     */
    public void sendData(String serialNumber, Message.Instruction instruction, SendEventHandler sendEvent) throws ServiceException {
        Channel channel = RegisterHandler.CHANNEL_MAP.get(serialNumber);
        if (channel == null) {
            log.warn("{}通道异常,序列号:{}", TAG, serialNumber);
            if (sendEvent != null) {
                sendEvent.sendError(instruction, new RuntimeException(TAG + "通道异常,序列号:" + serialNumber));
            } else {
                throw new ServiceException(TAG + "通道异常,序列号:" + serialNumber);
            }
        } else {
            if (sendEvent != null) {
                channel.writeAndFlush(instruction).addListeners((ChannelFutureListener) channelFuture -> {
                    if (channelFuture.isSuccess()) {
                        sendEvent.sendSucceed(instruction);
                    } else {
                        sendEvent.sendError(instruction, channelFuture.cause());
                    }
                });
            } else {
                channel.writeAndFlush(instruction);
            }
        }
    }

    /**
     * 功能描述:
     * 〈 断开连接 〉
     *
     * @param serialNumber 主机序列号
     * @return : void
     * @author : yls
     * @date : 2022/5/11 11:05
     */
    public void disconnect(String serialNumber) {
        Channel channel = RegisterHandler.CHANNEL_MAP.get(serialNumber);
        if (channel != null) {
            channel.close();
        }
    }

    @Override
    public void onApplicationEvent(ContextClosedEvent contextClosedEvent) {
        if (this.channel != null) {
            this.channel.closeFuture();
        }
        log.info("{}tcp服务端停止服务！", TAG);
    }

}
